<!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<div id="host1"></div>
<div id="host2"></div>
<div id="host3"></div>
<script>
    var root1 = host1.attachShadow({mode: 'open'});
    var root2 = host2.attachShadow({mode: 'open'});
    var root3 = host3.attachShadow({mode: 'open'});

    root1.innerHTML = `<style>#t1 + div + div + #r1 {background-color:green}</style>
        <div id="t1"></div>
        <div id="i1"></div>
        <div id="r1"></div>
        <div></div>`;

    root2.innerHTML = `<style>#t2 + div + div + #r2 {background-color:green}</style>
        <div id="i2"></div>
        <div></div>
        <div id="r2"></div>
        <div></div>`;

    root3.innerHTML = `<style>#t3 + div + div + #r3 {background-color:green}</style>
        <div id="t3"></div>
        <div></div>
        <div id="d3"></div>
        <div></div>
        <div id="r3"></div>
        <div></div>`;

    document.body.offsetTop;

    test(function() {
        assert_true(!!window.internals, "This test only works with internals exposed present");
    }, "internals are exposed");

    test(function() {
        var i1 = root1.querySelector('#i1');
        var r1 = root1.querySelector('#r1');
        assert_equals(getComputedStyle(r1).backgroundColor, "rgba(0, 0, 0, 0)", "Background color should initially be transparent");

        i1.parentNode.insertBefore(document.createElement('div'), i1);
        assert_equals(internals.updateStyleAndReturnAffectedElementCount(), 2, "Inserted div plus #r1 recalculated");
        assert_equals(getComputedStyle(r1).backgroundColor, "rgb(0, 128, 0)", "Background color is green after class change");
    }, "Insert between siblings");

    test(function() {
        var i2 = root2.querySelector('#i2');
        var r2 = root2.querySelector('#r2');
        assert_equals(getComputedStyle(r2).backgroundColor, "rgba(0, 0, 0, 0)", "Background color should initially be transparent");

        var t2 = document.createElement('div');
        t2.id = 't2';
        i2.parentNode.insertBefore(t2, i2);
        assert_equals(internals.updateStyleAndReturnAffectedElementCount(), 2, "Inserted div plus #r2 recalculated");
        assert_equals(getComputedStyle(r2).backgroundColor, "rgb(0, 128, 0)", "Background color is green after class change");
    }, "Insert before siblings");

    test(function() {
        var d3 = root3.querySelector('#d3');
        var r3 = root3.querySelector('#r3');

        d3.parentNode.removeChild(d3);
        assert_equals(internals.updateStyleAndReturnAffectedElementCount(), 1, "#r3 recalculated");
        assert_equals(getComputedStyle(r3).backgroundColor, "rgb(0, 128, 0)", "Background color is green after class change");
    }, "Remove between siblings");

</script>
